﻿using AutoMapper;
using Dm.util;
using Extentions;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.Useres;
using Management.Systeam.Read.Apis.Auto.UserDto;
using MediatR;
using SqlSugar;
using System.DirectoryServices.Protocols;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Useres
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, ApiResult<LoginDto>>
    {

        IBaseRepository<Users> Users;
        IBaseRepository<RoleUser> RoleUser;
        IBaseRepository<Role> Role;
        IConfiguration configuration;
        IMapper mapper;

        public LoginCommandHandler(IBaseRepository<Users> users, IBaseRepository<RoleUser> roleUser, IBaseRepository<Role> role, IMapper mapper, IConfiguration configuration)
        {
            Users = users;
            RoleUser = roleUser;
            Role = role;
            this.mapper = mapper;
            this.configuration = configuration;
        }

        public async Task<ApiResult<LoginDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            ApiResult<LoginDto> result = new ApiResult<LoginDto>();
            try
            {
                JwtTools jwtTools = new JwtTools();
                var list = Users.GetQuery().Where(x => x.User_Name == request.User_Name).First();
                var slist = Role.GetQuery().Where(x => x.Role_Id == list.Role_Id).First();
                if (list == null)
                {
                    result.Message = "用户名不存在";
                    result.Code = ApiEnum.error;
                    return await Task.FromResult(result);
                }
                LoginDto value = new LoginDto();
                if (list.User_PassWord == request.User_PassWord)
                {
                    result.Code = ApiEnum.success;
                    result.Message = "登录成功";
                    string Token = jwtTools.JwtNewString(configuration, list.UId.toString());
                    value.Rid = slist.Rid;
                    value.User_Name = request.User_Name;
                    value.Token = Token;
                    result.Data = value;
                }
                else
                {
                    result.Code = ApiEnum.error;
                    result.Message = "密码错误";
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.error;
                result.Message = ex.Message;

            }
            return result;
        }
    }
}
